package com.heima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.reggie.common.R;
import com.heima.reggie.common.SMSUtils;
import com.heima.reggie.common.ValidateCodeUtils;
import com.heima.reggie.domain.User;
import com.heima.reggie.dto.UserDto;
import com.heima.reggie.service.ShoppingCartService;
import com.heima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ShoppingCartService shoppingCartService;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user , HttpSession session){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)) {
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            log.info("手机验证码======{}", code);
            //session.setAttribute(phone, code);


            redisTemplate.opsForValue().set("reggiePhoneCode",code,1, TimeUnit.MINUTES);
//            String s = code.toString();
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,s);
            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto , HttpSession session){
        String phone = userDto.getPhone();
        Integer code = userDto.getCode();
//        String s = code.toString();
//        Integer codeInSession =(Integer) session.getAttribute(phone);
//        log.info("{}",codeInSession);

        Integer redisCode = (Integer) redisTemplate.opsForValue().get("reggiePhoneCode");

        if(StringUtils.isNotEmpty(phone) && redisCode.equals(code)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(userLambdaQueryWrapper);

            if(user == null){
                userService.save(userDto);
            }
            assert user != null;
            session.setAttribute("user",user.getId());
            redisTemplate.delete("reggiePhoneCode");
            return R.success("登陆成功");

        }
        return R.error("登陆失败");
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCartService.cleanShoppingCart(userId);
        session.removeAttribute("user");
        return R.success("退出成功");

    }

}
